import router, {allRoutes, errotRoutes, frontRoutes} from "./router"
// @ts-ignore
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from "@/stores";
import {getKeepAliveRoutes} from "@/router/routerMenu";
import {adminRouterPath} from "@/router/config";
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({showSpinner: false})

// 白名单列表
const whiteList = ["/login", "/"]


// 路由加载前
router.beforeEach(async (to, from, next) => {

        // set page title
        document.title = getPageTitle(to);

        NProgress.start();
        // token存在的情况
        if (store.userStore.token) {
            if (to.path === '/login') {
                next(adminRouterPath + '/index')
            } else {
                // 用户信息不存在，则重新拉取用户等信息
                if (store.userStore.user == null || !store.userStore.user.userId) {
                    await store.userStore.getUserInfoAction()
                    const menuRoutes = await store.routerStore.getMenuRoutes()
                    // 添加管理员菜单路由
                    allRoutes.children?.push(...menuRoutes)
                    router.addRoute(allRoutes)

                    // 错误路由
                    errotRoutes.forEach(function (item) {
                        router.addRoute(item);
                    })

                    // 保存路由数据
                    store.routerStore.setRoutes(frontRoutes.concat(allRoutes))

                    // 搜索菜单需要使用
                    const keepAliveRoutes = getKeepAliveRoutes(menuRoutes, [])
                    store.routerStore.setSearchMenu(keepAliveRoutes)

                    next({...to, replace: true})
                } else {
                    next()
                }
            }
        } else {
            // 没有token的情况下，可以进入白名单
            if (whiteList.indexOf(to.path) > -1) {
                next()
            } else {
                next('/login')
            }
        }
    }
)

// 路由加载后
router.afterEach(() => {
    NProgress.done()
})

